package com.summer.shopping.chat;

import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketSession;

import java.util.HashMap;
import java.util.concurrent.ConcurrentHashMap;

@Component
public class UserChatPool {

    private final ConcurrentHashMap<Long, WebSocketSession> userChatPool = new ConcurrentHashMap<>();
    private final ConcurrentHashMap<WebSocketSession, Long> reverseUserChatPool = new ConcurrentHashMap<>();


    public void addUser(Long userId, WebSocketSession webSocketSession) {
        userChatPool.put(userId, webSocketSession);
        reverseUserChatPool.put(webSocketSession, userId);
    }

    public void removeUser(Long userId) {
        WebSocketSession session = userChatPool.get(userId);
        reverseUserChatPool.remove(session);
        userChatPool.remove(userId);

    }

    public void removeUser(WebSocketSession webSocketSession) {
        Long userId = reverseUserChatPool.get(webSocketSession);
        userChatPool.remove(userId);
        reverseUserChatPool.remove(webSocketSession);
    }


    public WebSocketSession getUser(Long userId) {
        return userChatPool.get(userId);
    }

    public Long getUserId(WebSocketSession webSocketSession) {
        return reverseUserChatPool.get(webSocketSession);
    }

    public WebSocketSession getSession(Long userId) {
        return userChatPool.get(userId);
    }

    //获取聊天在线人数
    public Integer getUserCount() {
        return userChatPool.size();
    }


    public HashMap<String,Object> getInfo(){
        HashMap<String,Object> info = new HashMap<>();
        info.put("userCount",userChatPool.size());
        userChatPool.forEach((userId, webSocketSession) -> {
            HashMap<String, Object> map = new HashMap<>();
            map.put("userId",userId);
            map.put("ipInfo",webSocketSession.getRemoteAddress());
            map.put("sessionId",webSocketSession.getId());
            map.put("attributes",webSocketSession.getAttributes());
            info.put("用户: "+userId.toString(),map);
        });
        return info;
    }


}
